﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Text;
using System.Data;
using MINERP.BLL.PhotoRindGrid;
using MINERP.DAL;

using MINERP.COM;
using MINERP.DAL.PhotoRindGrid;
using MINERP.MODEL.FoundationModel;
using System.Diagnostics;


namespace MINERP.BLL.LeaderOperate
{
    public class LeaderTaskBLL
    {

        private MINERP.DAL.LeaderOperate.LeaderTaskDAL _dal = new DAL.LeaderOperate.LeaderTaskDAL();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="inDic"></param>
        /// <returns></returns>
        public DataTable GetTaskByleaderIdAndOper(Dictionary<int, string> inDic, out List<string> listPri, out List<string> statusList, out List<int> priorityIDList, out List<string> listTech)
        {
            List<string> priorityList = new List<string>();
            List<string> stutasList = new List<string>();
            List<string> techList = new List<string>();
            techList.Add("全部");
            techList.Add("当前");
            stutasList.Add("全部");
            string opers = changer(inDic);
            List<int> outIDList = new List<int>();
            //List<WorkOrderFlowList> useableFlow = _dal.GetTaskByStatusAndOpe((int)OrderFlowListStatus.Useable, opers);
            //string strOrderProducts = ChangerListToStringOrderProductID(useableFlow);
            //List<WorkOrderFlowList> lists = _dal.GetTaskByOrderIDAndOpe(strOrderProducts, opers);

            List<WorkOrderFlowList> accept = _dal.GetTaskByStatusAndOpe((int)OrderFlowListStatus.UseableAccept, opers);
            List<WorkOrderFlowList> Useable = _dal.GetTaskByStatusAndOpe((int)OrderFlowListStatus.Useable, opers);
            List<WorkOrderFlowList> errFlow = _dal.GetTaskByStatusAndOpe((int)OrderFlowListStatus.Error, opers);
            List<WorkOrderFlowList> waitFlow = _dal.GetTaskByStatusAndOpe((int)OrderFlowListStatus.Wait, opers);
            // ObjectQuery<WorkOrderFlowList> comFlow = _dal.GetTaskByStatusAndOpe((int) OrderFlowListStatus.Useable, opers);
            List<WorkOrderFlowList> lists = new List<WorkOrderFlowList>();
            lists = Useable.Union(accept).Union(waitFlow).Union(errFlow).ToList();
            DataTable rtnTable = CreateLeaderTaskTable();
            int MaxPriorty = 0;
            foreach (var flow in lists)
            {

                Stopwatch sw = new Stopwatch();
                sw.Start();
                #region 加载数据
                if (!flow.orderInfoReference.IsLoaded)
                {
                    flow.orderInfoReference.Load();
                }
                if (!flow.orderInfo.Tb_OrderBagReference.IsLoaded)
                {
                    flow.orderInfo.Tb_OrderBagReference.Load();
                }
                if (!flow.orderInfo.Tb_OrderBag.ShopReference.IsLoaded)
                {
                    flow.orderInfo.Tb_OrderBag.ShopReference.Load();
                }
                #endregion
                if (flow.orderInfo.status != (int)OrderInfoStatus.Doing)
                {
                    continue;
                }
                sw.Stop();
                Console.Write(sw.ToString());
                sw.Reset();
                sw.Start();
                DataRow row = rtnTable.NewRow();
                row["WorkFlowListId"] = flow.WorkFlowListId;
                row["OrderProductId"] = flow.orderInfo.OrderProductId;

                //flow.orderInfoReference.Load(MergeOption.AppendOnly);
                //flow.orderInfo.Tb_OrderBagReference.Load(MergeOption.AppendOnly);
                //flow.orderInfo.Tb_OrderBag.ShopReference.Load(MergeOption.AppendOnly);
                row["BagCode"] = flow.orderInfo.Tb_OrderBag.BagCode;
                row["BagName"] = flow.orderInfo.Tb_OrderBag.BagName;
                row["OrderProductCode"] = flow.orderInfo.OrderProductCode;
                row["OrderProductName"] = flow.orderInfo.OrderProductName;
                row["ShopName"] = flow.orderInfo.Tb_OrderBag.Shop.shopName;
                row["CtmName"] = flow.orderInfo.CtmName;
                row["OrderPath"] = flow.orderInfo.OrderPath;

                users u = _dal.GetUserById(flow.UserId);
                if (u == null)
                {
                    row["UserName"] = "未分配";
                }
                else
                {
                    row["UserName"] = u.UserName;
                }
                row["TechName"] = flow.tb_Tech.TechName;
                row["Priority"] = flow.orderInfo.Priority;
                if (flow.orderInfo.Tb_OrderBag.Priority > MaxPriorty)
                {
                    outIDList.Clear();
                    outIDList.Add(flow.WorkFlowListId);
                    MaxPriorty = flow.orderInfo.Tb_OrderBag.Priority;
                }
                else if (flow.orderInfo.Tb_OrderBag.Priority == MaxPriorty)
                {
                    outIDList.Add(flow.WorkFlowListId);
                }

                row["OrderBagId"] = flow.orderInfo.Tb_OrderBag.OrderBagId;
                switch (flow.Status)
                {
                    case (int)OrderFlowListStatus.Wait:
                        if (flow.UserId == 0)
                        {
                            row["status"] = "未分配";
                        }
                        else
                        {
                            row["status"] = "已分配";
                            row["AssignTime"] = Convert.ToDateTime(flow.AssignTime);
                            row["PreCompleteTime"] = Convert.ToDateTime(flow.PreCompleteTime);
                        }
                        row["IsCurrTech"] = "否";
                        break;
                    case (int)OrderFlowListStatus.Useable:
                        if (flow.UserId == 0)
                        {
                            row["status"] = "未分配";
                        }
                        else
                        {
                            row["status"] = "已分配";
                            row["AssignTime"] = Convert.ToDateTime(flow.AssignTime);
                        }
                        row["IsCurrTech"] = "是";
                        break;
                    case (int)OrderFlowListStatus.Error:
                        row["status"] = "异常";
                        row["IsCurrTech"] = "否";
                        break;
                    case (int)OrderFlowListStatus.Complete:
                        row["status"] = "完成";
                        row["IsCurrTech"] = "否";
                        break;
                    case (int)OrderFlowListStatus.UseableAccept:
                        {
                            row["status"] = "已接收";
                            row["ReceiveTime"] = Convert.ToDateTime(flow.ReceiveTime);
                            row["IsCurrTech"] = "否";
                        }

                        break;
                    default:
                        row["status"] = "未知";
                        row["IsCurrTech"] = "否";
                        break;
                }
                row["OrderTime"] = flow.orderInfo.Tb_OrderBag.OrderTime;
                row["CompletedTime"] = Convert.ToDateTime(flow.CompletedTime);
                rtnTable.Rows.Add(row);
                string strPriority = "";
                string strStutas = "";
                string strTech = "";
                strPriority = priorityList.Find(delegate(string a)
                {
                    if (a.Equals(flow.orderInfo.Tb_OrderBag.Priority.ToString()))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }

                });
                if (strPriority == null)
                {
                    priorityList.Add(flow.orderInfo.Tb_OrderBag.Priority.ToString());
                }
                strStutas = stutasList.Find(delegate(string b)
                {
                    if (b.Equals(row["status"].ToString()))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                });
                if (strStutas == null)
                {
                    stutasList.Add(row["status"].ToString());
                }
                strTech = techList.Find(delegate(string c)
                                            {
                                                if (c.Equals(row["TechName"].ToString()))
                                                {
                                                    return true;
                                                }
                                                else
                                                {
                                                    return false;
                                                }
                                            });
                if (strTech == null)
                {
                    techList.Add(row["TechName"].ToString());
                }
                sw.Stop();
                Console.Write(sw.ToString());
            }
            listTech = techList;
            listPri = priorityList;
            statusList = stutasList;
            priorityIDList = outIDList;
            DataRow[] rows = rtnTable.Select("", "OrderTime desc");
            DataTable sortTable = rtnTable.Clone();
            sortTable.Clear();
            foreach (DataRow row in rows)
            {
                sortTable.ImportRow(row);
            }
            return sortTable;
        }
        /// <summary>
        /// 测试版
        /// </summary>
        /// <param name="inDic"></param>
        /// <param name="listPri"></param>
        /// <param name="statusList"></param>
        /// <param name="priorityIDList"></param>
        /// <param name="listTech"></param>
        /// <returns></returns>
        public DataTable GetTaskByleaderIdAndOperUp(Dictionary<int, string> inDic,string workflowName,string status)
        {
            return _dal.GetTaskDataTable(status,workflowName, changer(inDic));
        }
        public List<string> GetTaskPrioritylist(Dictionary<int, string> inDic)
        {
            return _dal.GetTaskPrioritylist("", changer(inDic));
        }
        public List<string> GetTaskStatuslist(Dictionary<int, string> inDic)
        {
            return _dal.GetTaskStatuslist("", changer(inDic));
        }
        public List<string> GetTaskTechlist(Dictionary<int, string> inDic)
        {
            return _dal.GetTaskTechlist("", changer(inDic));
        }



        /// <summary>
        /// 取得所有orderProductid
        /// </summary>
        /// <param name="lists"></param>
        /// <returns></returns>
        private string ChangerListToStringOrderProductID(List<WorkOrderFlowList> lists)
        {
            string strVar = string.Empty;
            // string strTemp = string.Empty;
            string strRtn = string.Empty;

            foreach (var list in lists)
            {
                if (!list.orderInfoReference.IsLoaded)
                {
                    list.orderInfoReference.Load();
                }

                if (list.orderInfo.status == (int)OrderInfoStatus.Doing)
                {
                    strVar += "," + list.orderInfo.OrderProductId;
                }
            }
            if (strVar.StartsWith(","))
            {
                strVar = strVar.Substring(1);
            }
            strRtn = "{" + strVar + "}";
            if (strRtn.Equals("{}"))
                return "{0}";
            else
                return strRtn;
        }

        /// <summary>
        /// 将操作转换为Entity可用格式
        /// </summary>
        /// <param name="inDic"></param>
        /// <returns></returns>
        private string changer(Dictionary<int, string> inDic)
        {
            string strVar = string.Empty;
            // string strTemp = string.Empty;
            string strRtn = string.Empty;

            foreach (var dic in inDic.Keys)
            {
                strVar += "," + dic.ToString();
            }
            if (strVar.StartsWith(","))
            {
                strVar = strVar.Substring(1);
            }
            strRtn = "{" + strVar + "}";
            if (strRtn.Equals("{}"))
                return "{0}";
            else
                return strRtn;
        }
        /// <summary>
        /// 将操作转换为Entity可用格式
        /// </summary>
        /// <param name="inDic"></param>
        /// <returns></returns>
        private string changerTradition(Dictionary<int, string> inDic)
        {
            string strVar = string.Empty;
            // string strTemp = string.Empty;
            string strRtn = string.Empty;

            foreach (var dic in inDic.Keys)
            {
                strVar += "," + dic.ToString();
            }
            if (strVar.StartsWith(","))
            {
                strVar = strVar.Substring(1);
            }
            strRtn = "(" + strVar + ")";
            if (strRtn.Equals("()"))
                return "(0)";
            else
                return strRtn;
        }
        /// <summary>
        /// 取得员工列表
        /// </summary>
        /// <param name="inGroupId"></param>
        /// <returns></returns>
        public List<UserDDO> GetUsersByLeaderId(int inGroupId)
        {
            List<users> userses = _dal.GetUsersByLeaderId(inGroupId);
            List<UserDDO> listDDO = new List<UserDDO>();
            foreach (var list in userses)
            {
                list.tb_WorkerGroupReference.Load(MergeOption.AppendOnly);
                UserDDO ddo = new UserDDO();
                ddo.userID = list.userID;
                ddo.UserName = list.UserName;
                ddo.HeadPicPath = list.HeadPicPath;
                ddo.MaxTaskCount = list.MaxTaskCount;
                ddo.IsOnline = (bool)list.IsOnline;
                ddo.HeadPicPath = list.HeadPicPath;
                ddo.GroupName = list.tb_WorkerGroup.GroupName;
                ddo.LoginName = list.LoginName;
                listDDO.Add(ddo);
            }
            return listDDO;
        }
        /// <summary>
        /// q取得单个组员详情
        /// </summary>
        /// <param name="inUserId"></param>
        /// <returns></returns>
        public UserDDO GetUserById(int inUserId)
        {
            users user = _dal.GetUserById(inUserId);
            UserDDO ddo = new UserDDO();
            ddo.userID = user.userID;
            ddo.LoginName = user.LoginName;
            ddo.UserName = user.UserName;
            ddo.MaxTaskCount = user.MaxTaskCount;
            ddo.Task = GetTaskNumByUserId(inUserId);
            ddo.GroupName = user.tb_WorkerGroup.GroupName;
            ddo.HeadPicPath = user.HeadPicPath;
            return ddo;
        }

        /// <summary>
        /// 取得组员现有任务量                          温州修改
        /// </summary>
        /// <param name="inUserId"></param>
        /// <returns></returns>
        public double GetTaskNumByUserId(int inUserId)
        {
            ////int assion = _dal.GetUserCurrTask(inUserId, (int)OrderFlowListStatus.Useable).Count;
            ////int accept = _dal.GetUserCurrTask(inUserId, (int)OrderFlowListStatus.UseableAccept).Count;
            //////int wait = _dal.GetUserCurrTask(inUserId, (int)OrderFlowListStatus.Wait).Count;
            //////return assion + accept + wait;
            ////return assion + accept;

            //int photoNum = _dal.GetUserPhotoNum(inUserId, (int)OrderFlowListStatus.Useable, (int)OrderFlowListStatus.UseableAccept);

            //return photoNum;
            //int photoNumCurr = _dal.GetUserPhotoNum(inUserId, (int)OrderFlowListStatus.UseableAccept);
            //int photoNumAssion = _dal.GetUserPhotoNum(inUserId, (int)OrderFlowListStatus.Useable);
            //return photoNumCurr + photoNumAssion;
            return _dal.GetUserPhotoNum(inUserId);



        }
        /// <summary>
        /// 取得组员任务总量                          
        /// </summary>
        /// <param name="inUserId"></param>
        /// <returns></returns>
        public int GetTaskAllNumByUserId(int inUserId)
        {
            return _dal.GetUserPhotoNumAll(inUserId);


            //int photoNumCurr = _dal.GetUserPhotoNum(inUserId, (int)OrderFlowListStatus.UseableAccept);
            //int photoNumAssion = _dal.GetUserPhotoNum(inUserId, (int)OrderFlowListStatus.Useable);
            //int photoNumWait = _dal.GetUserPhotoNum(inUserId, (int)OrderFlowListStatus.Wait);

            //return photoNumCurr + photoNumAssion + photoNumWait;


        }
        /// <summary>
        /// 分配任务
        /// </summary>
        /// <param name="inUserId"></param>
        /// <param name="inOrderId"></param>
        public void AssignTsakByWorkerAndOrderID(int inUserId, int inOrderId)
        {
            WorkOrderFlowList flowList = _dal.GetTaskByStatusAndOrderId((int)OrderFlowListStatus.Useable, inOrderId);
            if (flowList.UserId == 0)
            {
                flowList.AssignTime = DateTime.Now;
                flowList.UserId = inUserId;
                _dal.Update();
            }
            else
            {

            }
        }

        /// <summary>
        /// 按ID分配任务
        /// </summary>
        /// <param name="inUserId"></param>
        /// <param name="inWorkerFlowsId"></param>
        public void AssignTsakByWorkerAndWorFlowID(int inUserId, int inWorkerFlowsId)
        {
            //WorkOrderFlowList flowList = _dal.GetTaskByWorkerFlowId(inWorkerFlowsId);

            //if (flowList.UserId == 0)
            //{
            //    flowList.AssignTime = DateTime.Now;
            //    flowList.UserId = inUserId;
            //    flowList.PreCompleteTime = DateTime.Now.AddHours(Convert.ToDouble(flowList.tb_Tech.NeedTime));
            //    _dal.Update();
            //}

            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                WorkOrderFlowList flowList = db.WorkOrderFlowList.FirstOrDefault(f => f.WorkFlowListId == inWorkerFlowsId);
                if (flowList != null)
                {
                    DateTime dateNow = DateTime.Now;
                    flowList.AssignTime =dateNow;
                    flowList.ReceiveTime = dateNow;
                    flowList.UserId = inUserId;
                    flowList.tb_TechReference.Load();
                    flowList.PreCompleteTime = DateTime.Now.AddHours(Convert.ToDouble(flowList.tb_Tech.NeedTime));
                    db.SaveChanges();
                }
            }
        }
        /// <summary>
        /// 按ID分配任务
        /// </summary>
        /// <param name="inUserId"></param>
        /// <param name="inWorkerFlowsId"></param>
        public void AssignTsakByWorkerAndWorFlowID1(int inUserId, int inWorkerFlowsId)
        {
            WorkOrderFlowList flowList = _dal.GetTaskByWorkerFlowId(inWorkerFlowsId);

            if (flowList.UserId == 0)
            {
                flowList.AssignTime = DateTime.Now;
                flowList.UserId = inUserId;
                flowList.PreCompleteTime = DateTime.Now.AddHours(Convert.ToDouble(flowList.tb_Tech.NeedTime));
                _dal.Update();
            }


        }
        /// <summary>
        /// 未完成任务列表
        /// </summary>
        /// <param name="inUserID"></param>
        /// <param name="Shop"></param>
        /// <param name="Customer"></param>
        /// <returns></returns>
        public DataTable GetUnCompleteTask(int inUserID)
        {
            return _dal.GetUserCurrTask(inUserID);
        }
        /// <summary>
        /// 未完成任务列表
        /// </summary>
        /// <param name="inUserID"></param>
        /// <param name="Shop"></param>
        /// <param name="Customer"></param>
        /// <returns></returns>
        public DataTable GetUnCompleteTask(int inUserID, out List<string> Shop, out List<string> Customer)
        {
            List<string> shopList = new List<string>();
            List<string> customerList = new List<string>();
            List<WorkOrderFlowList> assion = _dal.GetUserCurrTask(inUserID, (int)OrderFlowListStatus.Useable);
            List<WorkOrderFlowList> accept = _dal.GetUserCurrTask(inUserID, (int)OrderFlowListStatus.UseableAccept);
            List<WorkOrderFlowList> wait = _dal.GetUserCurrTask(inUserID, (int)OrderFlowListStatus.Wait);
            DataTable rtnTable = CreateLeaderTaskTable();
            foreach (var flow in accept.Union(assion).Union(wait))
            {

                DataRow row = rtnTable.NewRow();

                flow.orderInfoReference.Load(MergeOption.AppendOnly);
                flow.orderInfo.Tb_OrderBagReference.Load(MergeOption.AppendOnly);
                flow.orderInfo.Tb_OrderBag.ShopReference.Load(MergeOption.AppendOnly);
                flow.tb_TechReference.Load();
                row["WorkFlowListId"] = flow.WorkFlowListId;
                row["OrderProductId"] = flow.orderInfo.OrderProductId;
                row["BagCode"] = flow.orderInfo.Tb_OrderBag.BagCode;
                row["BagName"] = flow.orderInfo.Tb_OrderBag.BagName;
                row["OrderProductCode"] = flow.orderInfo.OrderProductCode;
                row["OrderProductName"] = flow.orderInfo.OrderProductName;
                row["ShopName"] = flow.orderInfo.Tb_OrderBag.Shop.shopName;
                row["CtmName"] = flow.orderInfo.CtmName;
                row["OrderPath"] = flow.orderInfo.OrderPath;
                if (string.IsNullOrEmpty(_dal.GetUserById(flow.UserId).UserName))
                {
                    row["UserName"] = "未分配";
                }
                else
                {
                    row["UserName"] = _dal.GetUserById(flow.UserId).UserName;
                }
                //row["UserName"] = _dal.GetUserById(flow.UserId).UserName;
                row["TechName"] = flow.tb_Tech.TechName;
                row["Priority"] = flow.orderInfo.Tb_OrderBag.Priority;
                row["OrderBagId"] = flow.orderInfo.Tb_OrderBag.OrderBagId;
                switch (flow.Status)
                {
                    case (int)OrderFlowListStatus.Wait:
                        {
                            row["status"] = "已分配";
                            row["AssignTime"] = Convert.ToDateTime(flow.AssignTime);

                        }

                        break;
                    case (int)OrderFlowListStatus.Useable:
                        if (flow.AssignTime.ToString().Equals(""))
                        {
                            row["status"] = "未分配";
                        }
                        else
                        {
                            row["status"] = "已分配";
                            row["AssignTime"] = Convert.ToDateTime(flow.AssignTime);
                        }
                        break;
                    case (int)OrderFlowListStatus.Error:
                        row["status"] = "异常";
                        break;
                    case (int)OrderFlowListStatus.Complete:
                        {
                            row["status"] = "完成";
                            row["CompletedTime"] = Convert.ToDateTime(flow.CompletedTime);
                        }
                        break;
                    case (int)OrderFlowListStatus.UseableAccept:
                        {
                            row["status"] = "已接收";
                            row["ReceiveTime"] = Convert.ToDateTime(flow.ReceiveTime);
                        }

                        break;
                    default:
                        row["status"] = "未知";
                        break;
                }
                row["OrderTime"] = flow.orderInfo.Tb_OrderBag.OrderTime;



                rtnTable.Rows.Add(row);
                string strShop = "";
                string strCustomer = "";
                strShop = shopList.Find(delegate(string a)
                                                    {
                                                        if (a.Equals(row["ShopName"].ToString()))
                                                        {
                                                            return true;
                                                        }
                                                        else
                                                        {
                                                            return false;
                                                        }

                                                    });
                if (strShop == null)
                {
                    shopList.Add(row["ShopName"].ToString());
                }
                strCustomer = customerList.Find(delegate(string b)
                                                {
                                                    if (b.Equals(row["CtmName"].ToString()))
                                                    {
                                                        return true;
                                                    }
                                                    else
                                                    {
                                                        return false;
                                                    }
                                                });
                if (strCustomer == null)
                {
                    customerList.Add(row["CtmName"].ToString());
                }
            }
            Shop = shopList;
            Customer = customerList;
            return rtnTable;
        }
        /// <summary>
        /// 根据组员Id 时间 类型等取得任务
        /// </summary>
        /// <param name="inWorkerId"></param>
        /// <param name="inStartTime"></param>
        /// <param name="inEndTime"></param>
        /// <param name="inType"></param>
        /// <param name="inStatus"></param>
        /// <param name="inShopName"></param>
        /// <param name="inCustomerName"></param>
        /// <param name="shop"></param>
        /// <param name="custumer"></param>
        /// <returns></returns>
        public DataTable GetWorkerTask(int inWorkerId, DateTime inStartTime, DateTime inEndTime, int inType, string inStatus, out List<string> shop, out List<string> custumer)
        {
            List<string> shopList = new List<string>();
            List<string> customerList = new List<string>();
            int status = 0;
            if (inStatus.Equals("已分配"))
            {
                status = 1;
            }
            else if (inStatus.Equals("已接收"))
            {
                status = 2;
            }
            else
            {
                status = 4;
            }
            List<WorkOrderFlowList> workOrderFlowLists = _dal.GetMemberOrders(inWorkerId, status, inStartTime,
                                                                                     inEndTime, inType);
            DataTable rtnTable = CreateLeaderTaskTable();
            foreach (WorkOrderFlowList flow in workOrderFlowLists)
            {
                DataRow row = rtnTable.NewRow();
                row["WorkFlowListId"] = flow.WorkFlowListId;
                row["OrderProductId"] = flow.orderInfo.OrderProductId;
                flow.orderInfoReference.Load(MergeOption.AppendOnly);
                flow.orderInfo.Tb_OrderBagReference.Load(MergeOption.AppendOnly);
                flow.orderInfo.Tb_OrderBag.ShopReference.Load(MergeOption.AppendOnly);
                flow.tb_TechReference.Load();
                row["BagCode"] = flow.orderInfo.Tb_OrderBag.BagCode;
                row["BagName"] = flow.orderInfo.Tb_OrderBag.BagName;
                row["OrderProductCode"] = flow.orderInfo.OrderProductCode;
                row["OrderProductName"] = flow.orderInfo.OrderProductName;
                row["ShopName"] = flow.orderInfo.Tb_OrderBag.Shop.shopName;
                row["CtmName"] = flow.orderInfo.CtmName;
                row["OrderPath"] = flow.orderInfo.OrderPath;
                if (string.IsNullOrEmpty(_dal.GetUserById(flow.UserId).UserName))
                {
                    row["UserName"] = "未分配";
                }
                else
                {
                    row["UserName"] = _dal.GetUserById(flow.UserId).UserName;
                }
                //row["UserName"] = _dal.GetUserById(flow.UserId).UserName;
                row["TechName"] = flow.tb_Tech.TechName;
                row["Priority"] = flow.orderInfo.Tb_OrderBag.Priority;
                row["OrderBagId"] = flow.orderInfo.Tb_OrderBag.OrderBagId;
                switch (flow.Status)
                {
                    case (int)OrderFlowListStatus.Wait:
                        row["status"] = "未激活";
                        break;
                    case (int)OrderFlowListStatus.Useable:
                        if (flow.AssignTime.ToString().Equals(""))
                        {
                            row["status"] = "未分配";
                        }
                        else
                        {
                            row["status"] = "已分配";
                        }
                        break;
                    case (int)OrderFlowListStatus.Error:
                        row["status"] = "异常";
                        break;
                    case (int)OrderFlowListStatus.Complete:
                        row["status"] = "完成";
                        break;
                    case (int)OrderFlowListStatus.UseableAccept:
                        row["status"] = "已接收";
                        break;
                    default:
                        row["status"] = "未知";
                        break;
                }
                row["OrderTime"] = flow.orderInfo.Tb_OrderBag.OrderTime;
                row["AssignTime"] = Convert.ToDateTime(flow.AssignTime);
                row["ReceiveTime"] = Convert.ToDateTime(flow.ReceiveTime);
                row["CompletedTime"] = Convert.ToDateTime(flow.CompletedTime);
                rtnTable.Rows.Add(row);
                string strShop = "";
                string strCustomer = "";
                strShop = shopList.Find(delegate(string a)
                {
                    if (a.Equals(row["ShopName"].ToString()))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }

                });
                if (strShop == null)
                {
                    shopList.Add(row["ShopName"].ToString());
                }
                strCustomer = customerList.Find(delegate(string b)
                {
                    if (b.Equals(row["CtmName"].ToString()))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                });
                if (strCustomer == null)
                {
                    customerList.Add(row["CtmName"].ToString());
                }


            }
            shop = shopList;
            custumer = customerList;
            return rtnTable;

        }

        public DataTable GetWorkerTaskTime(int inWorkerId, DateTime inStartTime, DateTime inEndTime, int inType, out List<string> shop, out List<string> custumer)
        {
            List<string> shopList = new List<string>();
            List<string> customerList = new List<string>();


            List<WorkOrderFlowList> workOrderFlowListsUnAcc = _dal.GetMemberOrders(inWorkerId, 1, inStartTime,
                                                                                     inEndTime, inType);
            List<WorkOrderFlowList> workOrderFlowListsAcc = _dal.GetMemberOrders(inWorkerId, 2, inStartTime,
                                                                                     inEndTime, inType);
            DataTable rtnTable = CreateLeaderTaskTable();
            foreach (WorkOrderFlowList flow in workOrderFlowListsUnAcc.Union(workOrderFlowListsAcc))
            {
                DataRow row = rtnTable.NewRow();
                row["WorkFlowListId"] = flow.WorkFlowListId;
                row["OrderProductId"] = flow.orderInfo.OrderProductId;
                flow.orderInfoReference.Load(MergeOption.AppendOnly);
                flow.orderInfo.Tb_OrderBagReference.Load(MergeOption.AppendOnly);
                flow.orderInfo.Tb_OrderBag.ShopReference.Load(MergeOption.AppendOnly);
                flow.tb_TechReference.Load();
                row["BagCode"] = flow.orderInfo.Tb_OrderBag.BagCode;
                row["BagName"] = flow.orderInfo.Tb_OrderBag.BagName;
                row["OrderProductCode"] = flow.orderInfo.OrderProductCode;
                row["OrderProductName"] = flow.orderInfo.OrderProductName;
                row["ShopName"] = flow.orderInfo.Tb_OrderBag.Shop.shopName;
                row["CtmName"] = flow.orderInfo.CtmName;
                row["OrderPath"] = flow.orderInfo.OrderPath;
                if (string.IsNullOrEmpty(_dal.GetUserById(flow.UserId).UserName))
                {
                    row["UserName"] = "未分配";
                }
                else
                {
                    row["UserName"] = _dal.GetUserById(flow.UserId).UserName;
                }
                //row["UserName"] = _dal.GetUserById(flow.UserId).UserName;
                row["TechName"] = flow.tb_Tech.TechName;
                row["Priority"] = flow.orderInfo.Tb_OrderBag.Priority;
                row["OrderBagId"] = flow.orderInfo.Tb_OrderBag.OrderBagId;
                switch (flow.Status)
                {
                    case (int)OrderFlowListStatus.Wait:
                        row["status"] = "未激活";
                        break;
                    case (int)OrderFlowListStatus.Useable:
                        if (flow.AssignTime.ToString().Equals(""))
                        {
                            row["status"] = "未分配";
                        }
                        else
                        {
                            row["status"] = "已分配";
                        }
                        break;
                    case (int)OrderFlowListStatus.Error:
                        row["status"] = "异常";
                        break;
                    case (int)OrderFlowListStatus.Complete:
                        row["status"] = "完成";
                        break;
                    case (int)OrderFlowListStatus.UseableAccept:
                        row["status"] = "已接收";
                        break;
                    default:
                        row["status"] = "未知";
                        break;
                }
                row["OrderTime"] = flow.orderInfo.Tb_OrderBag.OrderTime;
                row["AssignTime"] = Convert.ToDateTime(flow.AssignTime);
                row["ReceiveTime"] = Convert.ToDateTime(flow.ReceiveTime);
                row["CompletedTime"] = Convert.ToDateTime(flow.CompletedTime);
                rtnTable.Rows.Add(row);
                string strShop = "";
                string strCustomer = "";
                strShop = shopList.Find(delegate(string a)
                {
                    if (a.Equals(row["ShopName"].ToString()))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }

                });
                if (strShop == null)
                {
                    shopList.Add(row["ShopName"].ToString());
                }
                strCustomer = customerList.Find(delegate(string b)
                {
                    if (b.Equals(row["CtmName"].ToString()))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                });
                if (strCustomer == null)
                {
                    customerList.Add(row["CtmName"].ToString());
                }


            }
            shop = shopList;
            custumer = customerList;
            return rtnTable;

        }
        public DataTable GetWorkerTaskTime(int inWorkerId, DateTime inStartTime, DateTime inEndTime, int inType)
        {
            return _dal.GetMemberOrdersNew(inWorkerId, inStartTime, inEndTime, inType);
        }
        /// <summary>
        /// 获取历史任务列表
        /// </summary>
        /// <param name="inUserId"></param>
        /// <param name="inProductId"></param>
        /// <param name="inOperate"></param>
        /// <returns></returns>
        public List<FlowsDDO> GetFlowHistoryList(int inUserId, int inProductId, Dictionary<int, string> inOperate)
        {
            string Operates = changer(inOperate);
            List<FlowsDDO> flowsDdo = new List<FlowsDDO>();
            List<WorkOrderFlowList> flowLists = _dal.GetFlowHistoryList(inProductId, Operates);
            foreach (WorkOrderFlowList list in flowLists)
            {
                FlowsDDO flow = new FlowsDDO();
                flow.TechName = list.tb_Tech.TechName;
                flow.GroupName = GetUserById(inUserId).GroupName;
                flow.StartTime = Convert.ToDateTime((list.AssignTime));
                flow.EndTime = Convert.ToDateTime(list.CompletedTime);
                flow.UserName = _dal.GetUserById(list.UserId) == null ? "" : _dal.GetUserById(list.UserId).UserName;
                switch (list.Status)
                {
                    case (int)OrderFlowListStatus.Wait:
                        flow.Status = "未激活";
                        break;
                    case (int)OrderFlowListStatus.Useable:
                        if (flow.StartTime.ToString().Equals(""))
                        {
                            flow.Status = "未分配";
                        }
                        else
                        {
                            flow.Status = "已分配";
                        }
                        break;
                    case (int)OrderFlowListStatus.Error:
                        flow.Status = "异常";
                        break;
                    case (int)OrderFlowListStatus.Complete:
                        flow.Status = "完成";
                        break;
                    case (int)OrderFlowListStatus.UseableAccept:
                        flow.Status = "已接收";
                        break;
                    default:
                        flow.Status = "未知";
                        break;
                }
                flowsDdo.Add(flow);


            }
            return flowsDdo;

        }
        /// <summary>
        /// 取得定单信息
        /// </summary>
        /// <param name="inProductId"></param>
        /// <param name="inDic"></param>
        /// <returns></returns>
        public OrderInfoDDO GetOrderInfos(int inProductId, Dictionary<int, string> inDic)
        {
            string oper = changer(inDic);
            orderInfo order = _dal.GetorderInfoById(inProductId);
            OrderInfoDDO outDdo = new OrderInfoDDO();
            order.Tb_OrderBag.ShopReference.Load();
            outDdo.OrderName = order.Tb_OrderBag.BagName;
            outDdo.OrderBarCode = order.Tb_OrderBag.BagCode;
            outDdo.ShopName = order.Tb_OrderBag.Shop.shopName;
            outDdo.Customer = order.CtmName;
            outDdo.OrderTime = order.Tb_OrderBag.OrderTime;
            outDdo.FachTime = order.Tb_OrderBag.FetchTime;
            outDdo.Priority = order.Tb_OrderBag.Priority;
            outDdo.CurrFlow = _dal.GetCurrTech(inProductId, oper);
            outDdo.ArriveDate = _dal.GetArriveTime(inProductId, oper);
            outDdo.OrderPath = order.OrderPath;
            return outDdo;
        }
        /// <summary>
        /// 取消任务
        /// </summary>
        /// <param name="inUserId"></param>
        /// <param name="inOrderId"></param>
        public void CancelTask(int inWorkFlowListId)
        {
            //WorkOrderFlowList flowList = _dal.GetTaskByStatusAndOrderId(inStatus, inOrderId);
            WorkOrderFlowList flowList = _dal.GetTaskByWorkerFlowId(inWorkFlowListId);


            flowList.AssignTime = null;
            flowList.UserId = 0;
            //flowList.Status = 1;
            flowList.ReceiveTime = null;

            _dal.Update();
            //using (newSampleYPDBEntities ds=new newSampleYPDBEntities())
            //{
            //  WorkOrderFlowList workOrderFlowList = ds.WorkOrderFlowList.Where(p => p.WorkFlowListId == inWorkFlowListId).FirstOrDefault();
            //    workOrderFlowList.AssignTime = null;
            //    workOrderFlowList.ReceiveTime = null;
            //    workOrderFlowList.PreCompleteTime = null;
            //    workOrderFlowList.CompletedTime = null;
            //    workOrderFlowList.UserId = 0;
            //    ds.SaveChanges();
            //}

        }

        public void CancelTaskFlow(WorkOrderFlowList inWorkFlow)
        {
            //WorkOrderFlowList flowList = _dal.GetTaskByStatusAndOrderId(inStatus, inOrderId);
            inWorkFlow.AssignTime = null;
            inWorkFlow.UserId = 0;
            _dal.Update();

        }
        public Dictionary<string, string> GetPhotoPath(int inOrderId)
        {
            orderInfo info = _dal.GetorderInfoById(inOrderId);
            Dictionary<string, string> outDic = new Dictionary<string, string>();
            outDic.Add(info.OrderProductName, info.OrderPath);
            return outDic;
        }
        /// <summary>
        /// 获得照片列表
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public List<PhotoView> GetPhotosList(int productId)
        {
            PhotoRindGridDAL prgdal = new PhotoRindGridDAL();

            List<PhotoView> retLists = new List<PhotoView>();
            List<photoInfo> photoInfos = prgdal.GetPhotoOfProduct(productId);
            foreach (photoInfo list in photoInfos)
            {
                PhotoView view = new PhotoView();
                view.PhotoInfo = new PhotoInfo_Info() { PhotoBarCode = list.PhotoBarCode, PhotoName = list.photoName, Width = list.Width, Height = list.Height, TotalNum = (int)list.TotalNum };

                retLists.Add(view);
            }
            return retLists;
        }

        /// <summary>
        /// 取得绑定商户
        /// </summary>
        /// <returns></returns>
        public List<ShopDDO> GetShops()
        {
            ObjectQuery<Shop> shops = _dal.GetAllShopInfo();
            List<ShopDDO> list = new List<ShopDDO>();
            foreach (Shop shop in shops)
            {
                ShopDDO shopDdo = new ShopDDO();
                shopDdo.shopId = shop.ShopId;
                shopDdo.shopName = shop.shopName;
                list.Add(shopDdo);
            }
            return list;

        }
        /// <summary>
        /// 取得历史记录条数
        /// </summary>
        /// <param name="inCondition"></param>
        /// <param name="oper"></param>
        /// <returns></returns>
        public int[] GetPageCount(string inCondition, Dictionary<int, string> inOper, int inCountInPage)
        {
            string oper = changer(inOper);
            return _dal.GetPageCount(inCondition, oper, inCountInPage);
        }

        /// <summary>
        /// 取得历史记录
        /// </summary>
        /// <param name="inCondition"></param>
        /// <param name="inCurrPage"></param>
        /// <param name="inOper"></param>
        /// <param name="inCountInPage"></param>
        /// <returns></returns>
        public List<RecordDDO> GetHistoryList(string inCondition, int inCurrPage, Dictionary<int, string> inOper, int inCountInPage)
        {
            string oper = changer(inOper);
            List<RecordDDO> records = _dal.GetHistoryList(inCondition, inCurrPage, oper, inCountInPage);
            return records;
        }
        /// <summary>
        /// 自动分配任务
        /// </summary>
        /// <param name="inGroupId">组Id</param>
        /// <param name="inLeaderId">组长Id</param>
        /// <param name="inOper">操作权限</param>
        /// <param name="inFullNum">满任务数量</param>
        /// <returns></returns>
        public int AutoAssionTask(int inGroupId, int inLeaderId, Dictionary<int, string> inOper, int inFullNum)
        {
            string oper = changer(inOper);
            //_dal.GetOneWorkFlowCurr(oper);
            //_dal.GetOneWorkFlowWait(oper);
            // int oper1 = inOper.Keys.;

            int Count = 0;
            #region

            //{
            //    return -1;//组员任务全满
            //}

            //int techCurrId = 0;

            //int intCurrFlowId = _dal.GetOneWorkFlowCurr(oper, out techCurrId);
            //int intWaitUserId = _dal.GetOneUserUnFull(inFullNum, inGroupId, techCurrId);
            //if (!isContineLeader && intWaitUserId == inLeaderId)
            //{
            //    continue;//跳过组长
            //}
            ////if (intWaitUserId==0)
            //if (intCurrFlowId != 0)
            //{
            //    AssignTsakByWorkerAndWorFlowID(intWaitUserId, intCurrFlowId);
            //    continue;
            //}
            //if (intWaitUserId == 0 || intCurrFlowId==0)
            //{
            //    int intWaitFlowId = _dal.GetOneWorkFlowWait(oper, out techCurrId);
            //    intWaitUserId = _dal.GetOneUserUnFull(inFullNum, inGroupId, techCurrId);
            //    if (intWaitFlowId != 0)
            //    {
            //        AssignTsakByWorkerAndWorFlowID(intWaitUserId, intWaitFlowId);
            //        continue;
            //    }
            //    else
            //    {
            //        return -2;//无任务可分
            //    }


            //}

            #endregion

            while (true)
            {
                List<int> techs = new List<int>();

                //List<users> usersCurr = _dal.GetOneUserUnFull(inFullNum, inGroupId, out techs);
                //if (usersCurr.Count == 0)
                //{
                //    return Count;
                //}

                //string strOper = changerListToString(techs);
                int outOrderProductId = 0;
                int intFlowId = _dal.GetOneWorkFlowCurr(oper, out outOrderProductId);///加急
                //if (intFlowId == 0)
                //{
                //    intFlowId = _dal.GetOneWorkFlowWait(strOper, out outOrderProductId);

                ///按客户查找
                /// 福州需求

                if (intFlowId == 0)
                {
                    return Count;
                }
                //}
                WorkOrderFlowList currFlow = _dal.GetTaskByWorkerFlowId(intFlowId);

                currFlow.tb_TechReference.Load();

                currFlow.orderInfoReference.Load();
                orderInfo orderProduct = currFlow.orderInfo;
                List<orderInfo> listProduct = _dal.GetProductByCtmName(orderProduct.CtmName);

                int intUserOld = 0;
                foreach (orderInfo info in listProduct)
                {
                    foreach (var dic in inOper.Keys)
                    {
                        info.WorkOrderFlowList.Load();
                        // info.WorkOrderFlo
                        WorkOrderFlowList flowList = info.WorkOrderFlowList.Where(p => p.tb_Tech.TechId == dic && p.UserId != 0).FirstOrDefault();
                        if (flowList != null)
                        {
                            List<int> userTechs = _dal.GetUserTechidsByUserId(flowList.UserId);
                            if (userTechs.Contains(dic))//检查下组员是否能做次任务设计修片一般不是同一人做
                            {
                                users u = _dal.GetUserById(flowList.UserId);
                                if (u.IsOnline)//检查是否在线
                                {
                                    intUserOld = flowList.UserId;
                                    break;
                                }

                            }



                        }
                    }
                    if (intUserOld != 0)
                    {
                        break;
                    }
                }
                if (intUserOld == 0)
                {
                    int currTechid=currFlow.tb_Tech.TechId;
                    int userNew = _dal.GetOneUserLeastTask(inFullNum, inGroupId, currTechid);//取得任务不满并且任务最少的组员
                    if (userNew == 0)
                    {
                        return Count;
                    }
                    else
                    {
                        AssignTsakByWorkerAndWorFlowID1(userNew, intFlowId);
                        Count++;
                    }

                }
                else
                {
                    AssignTsakByWorkerAndWorFlowID1(intUserOld, intFlowId);
                    Count++;
                }

                #region
                /*
                int lastUserid = _dal.GetUserOperLast(outOrderProductId, strOper);///产品上步操作人
                if (lastUserid != 0)
                {
                    int flag = 0;
                    foreach (users user in usersCurr)
                    {

                        if (user.userID == lastUserid)
                        {
                            AssignTsakByWorkerAndWorFlowID(lastUserid, intFlowId);
                            flag = 1;
                            Count++;
                            break;
                        }
                        //user.tb_Tech.Load();
                        //List<tb_Tech> techList = user.tb_Tech.ToList();
                        //int flag = 0;
                        //foreach (tb_Tech tech in techList)
                        //{
                        //    if (tech.TechId == currFlow.tb_Tech.TechId && user.userID == lastUserid)
                        //    {
                        //        AssignTsakByWorkerAndWorFlowID(lastUserid, intFlowId);
                        //        flag=1;
                        //        break;
                        //    }

                        //}

                    }
                    if (flag == 0)///找到上步操作人但是操作人任务已满
                    {
                        foreach (users user in usersCurr)
                        {
                            user.tb_Tech.Load();
                            List<tb_Tech> techList = user.tb_Tech.ToList();
                            int flag1 = 0;
                            foreach (tb_Tech tech in techList)
                            {
                                if (tech.TechId == currFlow.tb_Tech.TechId)
                                {
                                    AssignTsakByWorkerAndWorFlowID(user.userID, intFlowId);
                                    flag1 = 1;
                                    Count++;
                                    break;
                                }

                            }
                            if (flag1 == 1)
                            {
                                break;
                            }
                        }
                    }


                }
                else//该产品第一次进组
                {
                    foreach (users user in usersCurr)
                    {
                        user.tb_Tech.Load();
                        List<tb_Tech> techList = user.tb_Tech.ToList();
                        int flag = 0;
                        foreach (tb_Tech tech in techList)
                        {
                            if (tech.TechId == currFlow.tb_Tech.TechId)
                            {
                                AssignTsakByWorkerAndWorFlowID(user.userID, intFlowId);
                                flag = 1;
                                Count++;
                                break;
                            }

                        }
                        if (flag == 1)
                        {
                            break;
                        }
                    }
                }
                */
                #endregion

            }

        }

        /// <summary>
        /// 自动分配任务
        /// </summary>
        /// <param name="inGroupId">组Id</param>
        /// <param name="inLeaderId">组长Id</param>
        /// <param name="inOper">操作权限</param>
        /// <param name="inFullNum">满任务数量</param>
        /// <returns></returns>
        public int AutoAssionTask1(int inGroupId, int inLeaderId, Dictionary<int, string> inOper, int inFullNum)
        {
            string oper = changer(inOper);
            //_dal.GetOneWorkFlowCurr(oper);
            //_dal.GetOneWorkFlowWait(oper);

            int Count = 0;
            #region

            //{
            //    return -1;//组员任务全满
            //}

            //int techCurrId = 0;

            //int intCurrFlowId = _dal.GetOneWorkFlowCurr(oper, out techCurrId);
            //int intWaitUserId = _dal.GetOneUserUnFull(inFullNum, inGroupId, techCurrId);
            //if (!isContineLeader && intWaitUserId == inLeaderId)
            //{
            //    continue;//跳过组长
            //}
            ////if (intWaitUserId==0)
            //if (intCurrFlowId != 0)
            //{
            //    AssignTsakByWorkerAndWorFlowID(intWaitUserId, intCurrFlowId);
            //    continue;
            //}
            //if (intWaitUserId == 0 || intCurrFlowId==0)
            //{
            //    int intWaitFlowId = _dal.GetOneWorkFlowWait(oper, out techCurrId);
            //    intWaitUserId = _dal.GetOneUserUnFull(inFullNum, inGroupId, techCurrId);
            //    if (intWaitFlowId != 0)
            //    {
            //        AssignTsakByWorkerAndWorFlowID(intWaitUserId, intWaitFlowId);
            //        continue;
            //    }
            //    else
            //    {
            //        return -2;//无任务可分
            //    }


            //}

            #endregion

            while (true)
            {
                List<int> techs = new List<int>();

                List<users> usersCurr = _dal.GetOneUserUnFull(inFullNum, inGroupId, out techs);
                if (usersCurr.Count == 0)
                {
                    return Count;
                }
                string strOper = changerListToString(techs);
                int outOrderProductId = 0;
                int intFlowId = _dal.GetOneWorkFlowCurr(strOper, out outOrderProductId);///加急
                //if (intFlowId == 0)
                //{
                //    intFlowId = _dal.GetOneWorkFlowWait(strOper, out outOrderProductId);
                if (intFlowId == 0)
                {
                    return Count;
                }
                //}
                WorkOrderFlowList currFlow = _dal.GetTaskByWorkerFlowId(intFlowId);

                currFlow.tb_TechReference.Load();
                int lastUserid = _dal.GetUserOperLast(outOrderProductId, strOper);///产品上步操作人
                if (lastUserid != 0)
                {
                    int flag = 0;
                    foreach (users user in usersCurr)
                    {

                        if (user.userID == lastUserid)
                        {
                            AssignTsakByWorkerAndWorFlowID(lastUserid, intFlowId);

                            flag = 1;
                            Count++;
                            break;
                        }
                        //user.tb_Tech.Load();
                        //List<tb_Tech> techList = user.tb_Tech.ToList();
                        //int flag = 0;
                        //foreach (tb_Tech tech in techList)
                        //{
                        //    if (tech.TechId == currFlow.tb_Tech.TechId && user.userID == lastUserid)
                        //    {
                        //        AssignTsakByWorkerAndWorFlowID(lastUserid, intFlowId);
                        //        flag=1;
                        //        break;
                        //    }

                        //}

                    }
                    if (flag == 0)///找到上步操作人但是操作人任务已满
                    {
                        foreach (users user in usersCurr)
                        {
                            user.tb_Tech.Load();
                            List<tb_Tech> techList = user.tb_Tech.ToList();
                            int flag1 = 0;
                            foreach (tb_Tech tech in techList)
                            {
                                if (tech.TechId == currFlow.tb_Tech.TechId)
                                {
                                    AssignTsakByWorkerAndWorFlowID(user.userID, intFlowId);
                                    flag1 = 1;
                                    Count++;
                                    break;
                                }

                            }
                            if (flag1 == 1)
                            {
                                break;
                            }
                        }
                    }


                }
                else//该产品第一次进组
                {
                    foreach (users user in usersCurr)
                    {
                        user.tb_Tech.Load();
                        List<tb_Tech> techList = user.tb_Tech.ToList();
                        int flag = 0;
                        foreach (tb_Tech tech in techList)
                        {
                            if (tech.TechId == currFlow.tb_Tech.TechId)
                            {
                                AssignTsakByWorkerAndWorFlowID(user.userID, intFlowId);
                                flag = 1;
                                Count++;
                                break;
                            }

                        }
                        if (flag == 1)
                        {
                            break;
                        }
                    }
                }


            }
        }

        private static string changerListToString(List<int> techs)
        {
            string strVar = string.Empty;
            // string strTemp = string.Empty;
            string strRtn = string.Empty;

            foreach (int tech in techs)
            {
                strVar += "," + tech.ToString();
            }
            if (strVar.StartsWith(","))
            {
                strVar = strVar.Substring(1);
            }
            strRtn = "{" + strVar + "}";
            if (strRtn.Equals("{}"))
                return "{0}";
            else
                return strRtn;
        }
        /// <summary>
        /// 换班回收所有问操作的任务
        /// </summary>
        /// <param name="inGroupId"></param>
        public void CallBackTask(int inGroupId)
        {
            List<users> useList = _dal.GetUsersByLeaderId(inGroupId);
            foreach (users user in useList)
            {
                List<WorkOrderFlowList> lists = _dal.GetUnCompleteTaskByUserId(user.userID);
                foreach (WorkOrderFlowList list in lists)
                {
                    CancelTaskFlow(list);
                }
            }
        }
        /// <summary>
        /// 取得产品照片信息
        /// </summary>
        /// <param name="inProductId"></param>
        /// <returns></returns>
        public int GetPhotoNumByFlowId(int inFlowId)
        {
            WorkOrderFlowList flowList = _dal.GetTaskByWorkerFlowId(inFlowId);
            flowList.orderInfoReference.Load();
            int productId = flowList.orderInfo.OrderProductId;

            return _dal.GetPhotoNumByProductId(productId);
        }
        public int GetPhotoNumByFlowIds(string inStrFlowId)
        {


            return _dal.GetPhotoNumByFlowIDs(inStrFlowId);
        }
        public double GetAreasByStatus(Dictionary<int, string> inOper, int status)
        {
            string opr = changerTradition(inOper);
            return _dal.GetAreasByStatus(opr, status);
        }
        #region
        /// <summary>
        /// 创建组长任务列表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateLeaderTaskTable()
        {
            DataTable table = new DataTable();


            table.Columns.Add(new DataColumn("OrderBagId", typeof(int)));
            table.Columns.Add(new DataColumn("OrderProductId", typeof(int)));
            table.Columns.Add(new DataColumn("BagCode", typeof(string)));
            table.Columns.Add(new DataColumn("BagName", typeof(string)));
            table.Columns.Add(new DataColumn("OrderProductCode", typeof(string)));
            table.Columns.Add(new DataColumn("OrderProductName", typeof(string)));
            table.Columns.Add(new DataColumn("Priority", typeof(string)));

            table.Columns.Add(new DataColumn("ShopName", typeof(string)));
            table.Columns.Add(new DataColumn("CtmName", typeof(string)));
            table.Columns.Add(new DataColumn("TechName", typeof(string)));
            table.Columns.Add(new DataColumn("IsCurrTech", typeof(string)));

            table.Columns.Add(new DataColumn("OrderPath", typeof(string)));
            table.Columns.Add(new DataColumn("UserName", typeof(string)));
            table.Columns.Add(new DataColumn("status", typeof(string)));
            table.Columns.Add(new DataColumn("OrderTime", typeof(DateTime)));
            table.Columns.Add(new DataColumn("AssignTime", typeof(DateTime)));
            table.Columns.Add(new DataColumn("ReceiveTime", typeof(DateTime)));
            table.Columns.Add(new DataColumn("CompletedTime", typeof(DateTime)));
            table.Columns.Add(new DataColumn("WorkFlowListId", typeof(int)));
            table.Columns.Add(new DataColumn("PreCompleteTime", typeof(DateTime)));
            return table;
        }
        #endregion

        /// <summary>
        /// 自动分配任务
        /// </summary>
        /// <param name="inGroupId">组Id</param>
        /// <param name="inLeaderId">组长Id</param>
        /// <param name="inOper">操作权限</param>
        /// <param name="inFullNum">满任务数量</param>
        /// <returns></returns>
        public int AutoAssionTaskBll(int inGroupId, int inLeaderId, Dictionary<int, string> inOper, int inFullNum,bool isAssionToLeader)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
               // string oper = changer(inOper);


                int Count = 0;

                orderInfo currMaxPriOrder = null;
                while (true)
                {
                    List<int> techs = new List<int>();
                    int MaxPri = 0;
                    int IntWorkFlowListStatus = (int)OrderFlowListStatus.Useable;
                    int IntOrderDoingStatus = (int)OrderInfoStatus.Doing;
                    int IntWorkFlowListCompleteStatus=(int)OrderFlowListStatus.Complete;
                   
                    //取到该组长操作范围内的当前任务中加急级别最高，还未分配的产品
                    foreach (KeyValuePair<int, string> keyValuePair in inOper)
                    {
                        orderInfo currOrder =
                            db.orderInfo.Where(
                                p =>
                                (p.WorkOrderFlowList.Where(
                                    pt =>
                                    pt.tb_Tech.TechId == keyValuePair.Key && pt.Status == IntWorkFlowListStatus &&
                                    pt.UserId == 0).
                                     Count() > 0) && (p.status == IntOrderDoingStatus)).OrderByDescending(
                                         p => p.Priority).FirstOrDefault();
                        if (currOrder == null)
                        {
                            continue;
                        }
                        //if (currMaxPriOrder == null)
                        //{
                        //    currMaxPriOrder = currOrder;
                        //}
                        //else
                        //{
                        //    if (currMaxPriOrder.Priority < currOrder.Priority)
                        //    {
                        //        currMaxPriOrder = currOrder;
                        //    }
                        //}
                        currMaxPriOrder = currOrder;


                    
                        currMaxPriOrder.WorkOrderFlowList.Load();
                        WorkOrderFlowList currFlow =
                            currMaxPriOrder.WorkOrderFlowList.FirstOrDefault(p => p.Status == IntWorkFlowListStatus);
                        currFlow.tb_TechReference.Load();
                        //List<orderInfo> listProduct = db.orderInfo.Where(p => p.CtmName == currMaxPriOrder.CtmName).ToList();

                        int intUserOld = 0;
                        //foreach (orderInfo info in listProduct)
                        //{
                        //    foreach (var dic in inOper.Keys)
                        //    {
                        //        info.WorkOrderFlowList.Load();
                        //        // info.WorkOrderFlo
                        //        foreach (WorkOrderFlowList orderFlowList in info.WorkOrderFlowList)
                        //        {
                        //            orderFlowList.tb_TechReference.Load();
                        //        }
                        //        WorkOrderFlowList flowList =
                        //            info.WorkOrderFlowList.Where(p => p.tb_Tech.TechId == dic && p.UserId != 0).
                        //                FirstOrDefault();
                        //        if (flowList != null)
                        //        {
                        //            //List<int> userTechs = GetUserTechidsByUserId(flowList.UserId, db);
                        //            //if (userTechs.Contains(dic)) //检查下组员是否能做次任务设计修片一般不是同一人做
                        //            //{
                        //            users u = db.users.FirstOrDefault(p => p.userID == flowList.UserId);
                        //            u.tb_Tech.Load();
                        //            tb_Tech currtech = u.tb_Tech.FirstOrDefault(p => p.TechId == dic);

                        //            if (u.IsOnline && currtech != null) //检查是否在线和该组员能否做该活
                        //            {
                        //                intUserOld = flowList.UserId;
                        //                break;
                        //            }
                        //            //}
                        //        }

                        //    }
                        //    if (intUserOld != 0)
                        //    {
                        //        break;
                        //    }
                        //}

                        foreach (var dic in inOper.Keys)
                        {
                            //foreach (orderInfo info in listProduct)
                            //{
                            //    info.WorkOrderFlowList.Load();
                            //    foreach (WorkOrderFlowList orderFlowList in info.WorkOrderFlowList)
                            //    {
                            //        orderFlowList.tb_TechReference.Load();
                            //    }

                            //}
                            var userwoflGroup = db.WorkOrderFlowList.Where(p => p.tb_Tech.TechId == dic && p.Status == IntWorkFlowListCompleteStatus && p.orderInfo.CtmName == currMaxPriOrder.CtmName).GroupBy(pt => pt.UserId).ToList();//组长权限下的完成的并且和当前客人名字相同的任务，按用户分组。
                            foreach (var userGroup in userwoflGroup)
                            {
                                users olduser = db.users.FirstOrDefault(p=>p.userID==userGroup.Key);
                                olduser.tb_Tech.Load();
                                tb_Tech currtech = olduser.tb_Tech.FirstOrDefault(p => p.TechId == currFlow.tb_Tech.TechId);
                                if (olduser.IsOnline && currtech != null)
                                {
                                    intUserOld = olduser.userID;
                                    break;
                                }
                            }
                            if (intUserOld != 0)
                            {
                                break;
                            }

                        }
                        if (intUserOld == 0)
                        {
                            currFlow.tb_TechReference.Load();
                            int userNew = GetOneUserLeastTask(inFullNum, inGroupId, db, isAssionToLeader, currFlow.tb_Tech.TechId); //取得任务不满并且任务最少的组员
                            if (userNew == 0)
                            {
                                return Count;
                            }
                            else
                            {
                                //AssignTsakByWorkerAndWorFlowID1(userNew, currFlow.WorkFlowListId);
                                currFlow.AssignTime = DateTime.Now;
                                currFlow.UserId = userNew;
                                currFlow.PreCompleteTime = DateTime.Now.AddHours(Convert.ToDouble(currFlow.tb_Tech.NeedTime)); 
                                db.SaveChanges();
                                Count++;
                            }
                        }
                        else
                        {
                            //AssignTsakByWorkerAndWorFlowID1(intUserOld, currFlow.WorkFlowListId);
                            currFlow.AssignTime = DateTime.Now;
                            currFlow.UserId = intUserOld;
                            currFlow.PreCompleteTime = DateTime.Now.AddHours(Convert.ToDouble(currFlow.tb_Tech.NeedTime));
                            db.SaveChanges();
                            Count++;

                        }
                    }
                  // db.SaveChanges();
                    //if (currMaxPriOrder == null)
                    //{
                        //return Count;
                    //}
                }
            }

        }
        public int AutoAssionTaskBll2(int inGroupId, int inLeaderId, Dictionary<int, string> inOper, int inFullNum, bool isAssionToLeader)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                // string oper = changer(inOper);


                int Count = 0;

                //orderInfo currMaxPriOrder = null;
                while (true)
                {
                    List<int> techs = new List<int>();
                    int MaxPri = 0;
                    int IntWorkFlowListStatus = (int)OrderFlowListStatus.Useable;
                    int IntOrderDoingStatus = (int)OrderInfoStatus.Doing;
                    int IntWorkFlowListCompleteStatus = (int)OrderFlowListStatus.Complete;
                    List<orderInfo> listTaskOrder = new List<orderInfo>();
                    //取到该组长操作范围内的当前任务中加急级别最高，还未分配的产品
                    foreach (KeyValuePair<int, string> keyValuePair in inOper)//组长权限内一个权限一个权限的分配任务
                    {
                        List<orderInfo> currOrderList =
                            db.orderInfo.Where(
                                p =>
                                (p.WorkOrderFlowList.Where(
                                    pt =>
                                    pt.tb_Tech.TechId == keyValuePair.Key && pt.Status == IntWorkFlowListStatus &&
                                    pt.UserId == 0).
                                     Count() > 0) && (p.status == IntOrderDoingStatus)).OrderByDescending(
                                         p => p.Priority).ToList();//获取任务列表
                        if (currOrderList.Count == 0)
                        {
                            continue;
                        }

                        listTaskOrder.AddRange(currOrderList.Take(20));
                        //currMaxPriOrder = currOrder;

                        foreach (orderInfo currMaxPriOrder in listTaskOrder.OrderByDescending(order => order.Priority))
                        {
                            //orderInfo currMaxPriOrder = currOrderList.OrderByDescending(order => order.Priority).FirstOrDefault();//获取到加急级别最高的任务
                            currMaxPriOrder.WorkOrderFlowList.Load();
                            WorkOrderFlowList currFlow =
                                currMaxPriOrder.WorkOrderFlowList.FirstOrDefault(p => p.Status == IntWorkFlowListStatus);
                            currFlow.tb_TechReference.Load();


                            int intUserOld = 0;


                            //foreach (var dic in inOper.Keys)
                            //{
                            //组长权限下的完成的并且和当前客人名字相同的任务，按用户分组。
                            var userwoflGroup = db.WorkOrderFlowList.Where(p => p.tb_Tech.TechId == keyValuePair.Key && p.orderInfo.CtmName == currMaxPriOrder.CtmName).GroupBy(pt => pt.UserId).ToList();
                            foreach (var userGroup in userwoflGroup)
                            {
                                users olduser = db.users.FirstOrDefault(p => p.userID == userGroup.Key);
                                if (olduser == null)
                                {
                                    continue;
                                }
                                olduser.tb_Tech.Load();
                                tb_Tech currtech = olduser.tb_Tech.FirstOrDefault(p => p.TechId == currFlow.tb_Tech.TechId);
                                if (olduser.IsOnline && currtech != null)
                                {
                                    intUserOld = olduser.userID;
                                    break;
                                }
                            }
                            //if (intUserOld != 0)
                            //{
                            //    break;
                            //}

                            //}
                            //没人做过
                            if (intUserOld == 0)
                            {
                                currFlow.tb_TechReference.Load();
                                int userNew = GetOneUserLeastTask(inFullNum, inGroupId, db, isAssionToLeader, currFlow.tb_Tech.TechId); //取得任务不满并且任务最少的组员
                                if (userNew == 0)
                                {
                                    //return Count;
                                    continue;
                                }
                                else
                                {
                                    //AssignTsakByWorkerAndWorFlowID1(userNew, currFlow.WorkFlowListId);
                                    currFlow.AssignTime = DateTime.Now;
                                    currFlow.UserId = userNew;
                                    currFlow.PreCompleteTime = DateTime.Now.AddHours(Convert.ToDouble(currFlow.tb_Tech.NeedTime));
                                    db.SaveChanges();
                                    Count++;
                                }
                            }
                            else
                            {
                                //AssignTsakByWorkerAndWorFlowID1(intUserOld, currFlow.WorkFlowListId);
                                currFlow.AssignTime = DateTime.Now;
                                currFlow.UserId = intUserOld;
                                currFlow.PreCompleteTime = DateTime.Now.AddHours(Convert.ToDouble(currFlow.tb_Tech.NeedTime));
                                db.SaveChanges();
                                Count++;

                            }
                            // }
                        }
                    }
                    db.SaveChanges();
                    return Count;
                    
                    //if (currMaxPriOrder == null)
                    //{
                    //return Count;
                    //}
                }
            }
            

        }
        /// <summary>
        /// 获取组员能操作的节点
        /// </summary>
        /// <param name="inUserid"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public List<int> GetUserTechidsByUserId(int inUserid,newSampleYPDBEntities db)
        {
            List<int> rtnInt = new List<int>();
            
                users user = db.users.FirstOrDefault(p => p.userID == inUserid);
                user.tb_Tech.Load();
                List<tb_Tech> listTech = user.tb_Tech.ToList();
                foreach (tb_Tech tech in listTech)
                {
                    rtnInt.Add(tech.TechId);
                }
            
            return rtnInt;
        }
        /// <summary>
        /// 获取组内最少的任务组员
        /// </summary>
        /// <param name="inFullNum"></param>
        /// <param name="inGroupId"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public int GetOneUserLeastTask(int inFullNum, int inGroupId, newSampleYPDBEntities db, bool isAssionToLeader,int inTechid)
        {

            int intUseStatus = (int)OrderFlowListStatus.Useable;
            int orderProductStatus = (int)OrderInfoStatus.Doing;
            int min = 100;
            int rtnuserId = 0;
            List<users> userList = null;
            if (!isAssionToLeader)
            {
                userList =
                   db.users.Where(p => p.tb_WorkerGroup.GroupId == inGroupId && p.IsLeader == false && p.IsOnline == true).
                       ToList();
            }
            else
            {
                userList =db.users.Where(p => p.tb_WorkerGroup.GroupId == inGroupId && p.IsOnline == true).
                                      ToList();
            }
            //foreach (users user in userList)
            int iCount = 0;
            while(true)
            {
                if (iCount > userList.Count * 3)
                {
                    break;
                }
                Random ro = new Random();
                int iResult;

                iResult = ro.Next(userList.Count);
                users user = userList[iResult];
                if (!user.tb_Tech.IsLoaded)
                {
                    user.tb_Tech.Load();
                }
                tb_Tech currtech = user.tb_Tech.FirstOrDefault(p => p.TechId == inTechid);
                if (currtech == null)
                {
                    iCount++;
                    continue;
                    
                }
                int count =
                    db.WorkOrderFlowList.Where(
                        p =>
                        p.UserId == user.userID && p.Status == intUseStatus && p.orderInfo.status == orderProductStatus)
                        .Count();
                if (count == 0)
                {
                    rtnuserId = user.userID;
                    break;
                }
                if (count < inFullNum && count < min)
                {
                    min = count;
                    rtnuserId = user.userID;
                    break;
                }
                
                iCount++;
            }
            return rtnuserId;
        }

        /// <summary>
        /// 获得所有非实物节点ID
        /// </summary>
        /// <returns></returns>
        public List<int> GetNonexistenceTechIdList()
        {
            List<int> list = new List<int>();


            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                List<tb_Tech> techlist = db.tb_Tech.Where(t => t.TechType == (int)TechType.nonexistence || t.TechType == (int)TechType.TiaoSe || t.TechType == (int)TechType.GroupSample).ToList();
                foreach (var item in techlist)
                {
                    list.Add(item.TechId);
                }
            }
            return list;
 
        }

        /// <summary>
        /// 获取组内成员业绩
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public DataTable GetGroupEmployment(int userId, DateTime start, DateTime end)
        {
            List<int> userIdLsit = new List<int>();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                users user = db.users.First(u=>u.userID ==userId);
                if (!user.tb_WorkerGroupReference.IsLoaded)
                {
                    user.tb_WorkerGroupReference.Load();
                }
                tb_WorkerGroup group = db.tb_WorkerGroup.First(g=>g.GroupId ==user.tb_WorkerGroup.GroupId);
                if (!group.users.IsLoaded)
                {
                    group.users.Load();
                }
                userIdLsit = group.users.Select(u => u.userID).ToList();
                return _dal.GetPerfromances(start, end, userIdLsit);

            }
            
        }

        /// <summary>
        /// 设置加急级别
        /// </summary>
        /// <param name="orderProductIdList"></param>
        /// <param name="priority"></param>
        public void SetPriority(List<int> orderProductIdList, int priority)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                foreach (var item in orderProductIdList)
                {
                    orderInfo oi = db.orderInfo.FirstOrDefault(o=>o.OrderProductId ==item);
                    if (oi != null)
                    {
                        oi.Priority = priority;
                    }
                }
                db.SaveChanges();
            }
        }


     /// <summary>
     /// 暂停产品
     /// </summary>
     /// <param name="orderProductId">产品编号</param>
     /// <param name="status">0表示暂停，1表示恢复</param>
     /// <param name="remark">备注</param>
     /// <param name="userId">用户ID</param>
        public  void PauseOrderProduct(int orderProductId, int status, string remark, int userId)
        {

            System.Transactions.TransactionOptions options = new System.Transactions.TransactionOptions();
            options.Timeout = new TimeSpan(0, 0, 600);
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;

            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {


                if (db.Connection.State != System.Data.ConnectionState.Open)
                {
                    db.Connection.Open();
                }


                using (System.Data.Common.DbTransaction tran = db.Connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
                {
                    try
                    {
                        orderInfo info = db.orderInfo.FirstOrDefault(o => o.OrderProductId == orderProductId);
                        if (!info.Tb_OrderBagReference.IsLoaded)
                        {
                            info.Tb_OrderBagReference.Load();
                        }
                        if (!info.WorkOrderFlowList.IsLoaded)
                        {
                            info.WorkOrderFlowList.Load();
                        }
                        WorkOrderFlowList wfi = info.WorkOrderFlowList.FirstOrDefault(w => w.Status == 1);
                        if (wfi == null)
                        {
                            return;
                        }

                        if (!wfi.tb_TechReference.IsLoaded)
                        {
                            wfi.tb_TechReference.Load();
                        }


                        tb_Tech tech = wfi.tb_Tech;
                        if (tech == null)
                            return;

                        List<New_EmployeePerformance> listNEP = db.New_EmployeePerformance.Where(e => e.OrderproductId == info.OrderProductId).ToList();

                        if (status == 0)                           //停止
                        {
                            info.Tb_OrderBag.Status = (int)OrderBagStatus.ProductStop;
                            info.status = (int)COM.OrderInfoStatus.Stop;
                            listNEP.ForEach(p => p.Status = (int)COM.OrderInfoStatus.Stop);//修改人员业绩状态
                        }
                        else                                        //恢复
                        {
                            info.Tb_OrderBag.Status = (int)OrderBagStatus.Doing;
                            info.status = (int)OrderInfoStatus.Doing;
                            listNEP.ForEach(p => p.Status = (int)COM.OrderInfoStatus.Doing);//修改人员业绩状态
                        }


                        //停止(恢复)记录
                        CtmOperateRecord newRecord = new CtmOperateRecord();
                        newRecord.CreateTime = DateTime.Now;
                        newRecord.OperateType = status;
                        newRecord.orderInfo = info;
                        newRecord.Remark = remark;
                        newRecord.tb_Tech = tech;
                        newRecord.users = db.users.FirstOrDefault(u => u.userID == userId);
                        db.AddToCtmOperateRecord(newRecord);

                        db.SaveChanges();

                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        throw ex;
                    }
                }
            }


        }
    }

}
